package com.third.controller;

import com.third.entity.User;
import com.third.result.ResponseResult;
import com.third.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @PostMapping("/login")
                                        //默认以json格式字符串提价 @RequestBody  让字符串转换成对象
    public ResponseResult<String> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){

        //得到token
        String token1 = request.getHeader("authorization");
        if (token1 != null){
            return new ResponseResult<>(201,"请勿重复登陆",null);
        }

        //逻辑:用账号查询处结果,然后进行对比  假设已经查到
        if (user.getAccount().equals("zhangsan") && user.getPwd().equals("123")){
            logger.debug("登陆成功");

            //生成一个token(JWT) ,返回给前端浏览器
            String token = JwtUtil.generateToken(user.getAccount());

            //将token放到响应头
            response.setHeader("authorization",token);
            //将该响应头暴露给第三方
            response.setHeader("Access-Control-Expose-Headers","authorization");

            //返回结果
            return new ResponseResult<>(200,"success",null);
        }else {
            logger.debug("登陆失败");
            return new ResponseResult<>(500,"账号或者密码有误",null);
        }
    }
}
